package org.hackystat.devcathlon.ui.page.matches;

import java.io.Serializable;
import java.util.Comparator;
import org.hackystat.devcathlon.engine.event.EventScore;
import org.hackystat.devcathlon.engine.match.Match;
import org.hackystat.devcathlon.engine.match.MatchManager;

/**
 * Comparator class used to sort Event Scores by score.
 * 
 * @author John Zhou
 */
public class EventScoreComparator implements Comparator<Object>, Serializable {
  /** Support serialization. */
  private static final long serialVersionUID = 1L;
  /** Boolean for ascending or descending sort. */
  private boolean ascending;
  /** The name of the match. */
  private String matchName;
  
  /**
   * Instantiates a EventScoreComparator.
   * 
   * @param ascending The boolean for ascending or descending sort.
   * 
   * @param matchName The name of the match.
   */
  public EventScoreComparator(boolean ascending, String matchName) {
    this.ascending = ascending;
    this.matchName = matchName;
  }
  
  /**
   * Override compare so that Event Scores can be sorted by due date.
   * 
   * @param obj1 The first EventScore to be sorted.
   * @param obj2 The second EventScore to be sorted.
   * @return compare A negative, zero, or a positive integer corresponding to less than, equal to,
   * or greater than.
   */
  public int compare(Object obj1, Object obj2) {
    EventScore a = (EventScore) obj1;
    EventScore b = (EventScore) obj2;
    Match m = MatchManager.getInstance().getMatch(matchName);
    int compare = m.getEvent(b).computePoints(b) - m.getEvent(a).computePoints(a);
    if (!ascending) {
      compare *= -1;
    }
    return compare;
  }
}
